//
//  AFHTTPSessionManager+RequestField.m
//  FinancialStore
//
//  Created by zhenqiu on 17/2/21.
//  Copyright © 2017年 zhenqiu. All rights reserved.
//

#import "AFHTTPSessionManager+RequestField.h"
#import "AFHTTPSessionManager+log.h"

@implementation AFHTTPSessionManager (RequestField)


- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString
                             parameters:(nullable id)parameters
              constructingBodyWithBlock:(nullable void (^)(id <AFMultipartFormData> formData))block
                       withRequestFiled:(nullable void (^)(NSMutableURLRequest *request))requestFieldBlock
                               progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress
                                success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
                                failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure{
    
    NSError *serializationError = nil;
    NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:&serializationError];
    if(requestFieldBlock){
        
        requestFieldBlock(request);
    }
    
    if([AFHTTPSessionManager debugLog]){
        GYNLog(@"请求地址:%@",[NSString stringWithFormat:@"%@",request.URL]);
        GYNLog(@"请求参数:%@",parameters);
    }
    if (serializationError) {
        if (failure) {
            dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
                failure(nil, serializationError);
            });
        }
        
        return nil;
    }
    
    __block NSURLSessionDataTask *task = [self uploadTaskWithStreamedRequest:request progress:uploadProgress completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
        if (error) {
            if (failure) {
                failure(task, error);
            }
        } else {
            if (success) {
                success(task, responseObject);
            }
        }
    }];
    
    [task resume];
    
    return task;
   
    
}

@end
